package com.blog.aop;

import com.blog.common.Cons;
import com.blog.util.ToolUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.util.stream.Collectors;

/**
 * 初始化数据库
 *
 * @author jiafujun
 * 2020-05-27 16:38:49
 **/
@Component
@Order(value = 1)
public class MyStartupRunner implements CommandLineRunner {

    private static Logger logger = LoggerFactory.getLogger(MyStartupRunner.class);
    public static String imgFlie;
    @Override
    public void run(String... args) throws Exception {
        try {
            imgFlie = ToolUtil.getSystemType() ? Cons.STORAGE_PATH : Cons.STORAGE_LIUNX_PATH;
            // 声明驱动类型
            Class.forName("org.sqlite.JDBC");
            // 设置sqlite db文件存放基本目录
            String path = MyStartupRunner.class.getProtectionDomain().getCodeSource().getLocation().getFile().replace("file:/", "");
            if (!path.contains(".jar")) {
                //开发环境不进行下面的操作
                return;
            }
            path = path.substring(0, path.indexOf(".jar"));
            if (path.contains(":")) {
                path = path.substring(0, path.lastIndexOf("/") + 1);
            } else {
                path = "/" + path.substring(0, path.lastIndexOf("/") + 1);
            }
            logger.info("创建路径：" + path);
            File imgs = new File(imgFlie);
            if (!imgs.exists()) {
                imgs.mkdirs();
            }
            path = path + "blog.db";
            File file = new File(path);
            if (file.exists()) {
                return;
            }
            // 设置 sqlite文件路径，等同于mysql连接地址(jdbc:mysql://127.0.0.1:3306/test)
            String url = "jdbc:sqlite:" + path;
            // 获取连接 关键代码
            Connection connection = DriverManager.getConnection(url, "root", "123456");
            Statement statement = connection.createStatement();

            logger.info("----------------  创建数据库  ----------------");
            InputStream in = MyStartupRunner.class.getResourceAsStream("/blogdb/blog.sql");
            InputStreamReader input = new InputStreamReader(in, StandardCharsets.UTF_8);
            String sql = new BufferedReader(input).lines().collect(Collectors.joining("\n"));
            statement.executeUpdate(sql);
            logger.info("---------------- 初始化数据库 ----------------");
            statement.close();
            connection.close();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("建立Sqlite连接失败");
        }
    }
}
